package com.jhl.seckill.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhl.seckill.entity.User;
import com.jhl.seckill.vo.RespBean;
import org.springframework.boot.configurationprocessor.json.JSONException;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * user工具类，生成用户
 */

public class UserUtil {

    private static void createUser(int count) throws SQLException, ClassNotFoundException, IOException, JSONException {
        List<User> users = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            User user = new User();
            user.setId((long) (i + 1));
            user.setUsername("user" + i);
            user.setSalt("1a2b3c4d");
            user.setLoginCount(1);
            user.setPassword(MD5Util.inputPassToDBPass("123", user.getSalt()));
//            user.setRegisterDate();
            users.add(user);

        }
//        插入数据库
//        Connection connection=getConnection();
//        String sql="insert into user(login_count,username,salt,password,id) values(?,?,?,?,?)";
//        PreparedStatement preparedStatement=connection.prepareStatement(sql);
//        for (int i=0;i<users.size();++i){
//            User user=users.get(i);
//            preparedStatement.setInt(1,user.getLoginCount());
//            preparedStatement.setString(2,user.getUsername());
////            preparedStatement.setTimestamp(3,new Timestamp(user.getRegisterDate().getLong()));
//            preparedStatement.setString(3,user.getSalt());
//            preparedStatement.setString(4,user.getPassword());
//            preparedStatement.setLong(5,user.getId());
//            preparedStatement.addBatch();
//
//        }
//        preparedStatement.executeBatch();
//        preparedStatement.clearParameters();
//        connection.close();
//
//        System.out.println("insert to db");

        String urlStr = "http://localhost:8080/login/doLogin";
        File file = new File("C:\\Users\\JHL\\Desktop\\config.txt");
        if (file.exists()) {
            file.delete();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        randomAccessFile.seek(0);

        for (int i = 0; i < users.size(); ++i) {
            User user = users.get(i);
            URL url = new URL(urlStr);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            httpURLConnection.setRequestProperty("connection", "keep-alive");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);

            httpURLConnection.connect();

            HttpRequest.post(urlStr);

//            获取输出流对象，向服务器写数据
            OutputStream outputStream = httpURLConnection.getOutputStream();

            Map<String, String> map = new HashMap<>();
            map.put("username", user.getUsername());
            map.put("password", "123");
            String params = JSONUtil.toJsonStr(map);

//            String params="{\"username\":\"" + user.getUsername() + "\",\"password\":\"" + 123 + "\"}";
            System.out.println(params);

//            发送请求
            outputStream.write(params.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();

//            读取响应
            InputStream inputStream = httpURLConnection.getInputStream();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buff)) >= 0) {
                byteArrayOutputStream.write(buff, 0, len);
            }
            inputStream.close();
            byteArrayOutputStream.close();
            String response = byteArrayOutputStream.toString();
            ObjectMapper mapper = new ObjectMapper();
            RespBean respBean = mapper.readValue(response, RespBean.class);
            String uuid = (String) respBean.getObject();
            System.out.println("create uuid : " + user.getId());
            String row = user.getUsername() + "," + uuid;
            randomAccessFile.seek(randomAccessFile.length());
            randomAccessFile.write(row.getBytes());
            randomAccessFile.write("\r\n".getBytes());
            System.out.println("write to file : " + user.getId());

        }
        randomAccessFile.close();


    }

    private static Connection getConnection() throws ClassNotFoundException, SQLException {
        String url = "jdbc:mysql://localhost:3306/seckill?allowPublicKeyRetrieval=true&useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=" +
                "Asia/Shanghai";
        String username = "root";
        String password = "123";
        String driver = "com.mysql.cj.jdbc.Driver";
        Class.forName(driver);

        return DriverManager.getConnection(url, username, password);
    }

    private static void createUser2(int count) throws SQLException, ClassNotFoundException, IOException, JSONException {
        List<User> users = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            User user = new User();
            user.setId((long) (i + 1));
            user.setUsername("user" + i);
            user.setSalt("1a2b3c4d");
            user.setLoginCount(1);
            user.setPassword(MD5Util.inputPassToDBPass("123", user.getSalt()));
//            user.setRegisterDate();
            users.add(user);

        }

        Connection connection = getConnection();
        String sql = "insert into user(login_count,username,salt,password,id) values(?,?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < users.size(); ++i) {
            User user = users.get(i);
            preparedStatement.setInt(1, user.getLoginCount());
            preparedStatement.setString(2, user.getUsername());
//            preparedStatement.setTimestamp(3,new Timestamp(user.getRegisterDate().getLong()));
            preparedStatement.setString(3, user.getSalt());
            preparedStatement.setString(4, user.getPassword());
            preparedStatement.setLong(5, user.getId());
            preparedStatement.addBatch();

        }
        preparedStatement.executeBatch();
        preparedStatement.clearParameters();
        connection.close();

        System.out.println("insert to db");

        String urlStr = "http://localhost:8080/login/doLogin";
        File file = new File("C:\\Users\\JHL\\Desktop\\config.txt");
        if (file.exists()) {
            file.delete();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        randomAccessFile.seek(0);

        for (int i = 0; i < users.size(); ++i) {
            User user = users.get(i);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", user.getUsername());
            jsonObject.put("password", "123");

//            System.out.println(JSONUtil.toJsonStr(jsonObject));
            Map<String, String> heads = new HashMap<>();
            heads.put("Content-Type", "application/json;charset=UTF-8");
//            发送请求
            HttpResponse response = HttpRequest.post(urlStr)
                    .headerMap(heads, false)
                    .body(String.valueOf(jsonObject))
                    .timeout(5 * 60 * 1000)
                    .execute();


            String body = response.body();
            RespBean respBean = JSONUtil.toBean(body, RespBean.class);
//            System.out.println(respBean.getObject());

            System.out.println("create uuid : " + user.getId());

            randomAccessFile.seek(randomAccessFile.length());
            String row = user.getUsername() + "," + respBean.getObject();
            randomAccessFile.write(row.getBytes(StandardCharsets.UTF_8));
            randomAccessFile.write("\r\n".getBytes());
            System.out.println("write to file : " + user.getId());

        }
        randomAccessFile.close();


    }

    public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JSONException {

        createUser2(5000);
    }
}
